﻿using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using System.Xml.Linq;

namespace Red.Scripts.Project
{
    internal class PathConverter
    {
        public string DepotPath { get; private set; }
        public IDictionary<string,string> Mappings { get; private set; }

        public async Task Load( string workspaceRoot )
        {
            DepotPath = Path.Combine( workspaceRoot, "r6", "depot" );
            Mappings = await Task.Run( () => { return LoadMappings( DepotPath ); } );
        }

        public string ToResourcePath( string path )
        {
            if ( !Path.IsPathRooted( path ) )
                return path;

            if ( !path.StartsWith( DepotPath ) )
                return path;

            // + 1 to remove the directory separator
            path = path.Substring( DepotPath.Length + 1 );

            foreach ( var mapping in Mappings )
            {
                if ( path.StartsWith( mapping.Key ) )
                {
                    return mapping.Value + path.Substring( mapping.Key.Length );
                }
            }

            return path;
        }

        private IDictionary<string,string> LoadMappings( string workspaceRoot )
        {
            Dictionary<string, string> output = new Dictionary<string, string>();

            XDocument document = XDocument.Load( Path.Combine( workspaceRoot, "mapping.xml" ) );

            IEnumerable< XElement > mounts = document.Descendants( "mount" );

            foreach( XElement mount in mounts )
            {
                XElement diskPath = mount.Element( "diskPath" );
                XElement resPath = mount.Element( "resPath" );

                output[ diskPath.Value ] = resPath.Value;
            }

            return output;
        }
    }
}
